﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
using WebBHXH.Entities;
using System.IO;
using System.Data;
using GemBox.Spreadsheet;

namespace WebBHXH
{
    public partial class _Default : System.Web.UI.Page
    {
        List<MaBHYTTNModel> listMaBHYTTN;
        DataTable datatable;
        string maThe = "";
        string hoTen = "";
        string loaiBH = "0";

        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                GetData("1");
            }
        }

        private void GetData(string flag)
        {
            System.Net.WebRequest request = null;
            
            if(flag == "1")
            {
                request = System.Net.WebRequest.Create(""+Util.getUrl() + "Home/GetMaBHYTTNModel");
                GetLoaiBHModel();
            } else {
                string dotBH = "";
                try
                {
                    dotBH = Int16.Parse(txtDotBH.Text).ToString();
                }
                catch (Exception e)
                {
                    dotBH = (txtDotBH.Text == "") ? "" : "0";
                }
                request = System.Net.WebRequest.Create("" + Util.getUrl() + "Home/SearchBHYTTNModel?maThe=" + txtMathe.Text + "&hoTen=" + txtHoTen.Text + "&loaiBH=" + ddlLoaiBH.SelectedValue + "&dotBh=" + dotBH + "&mucBH=0");
            }
            
            request.Method = "POST";
            request.ContentLength = 0;
            request.ContentType = "application/json; charset=utf-8";
            //get response-stream, and use a streamReader to read the content
            listMaBHYTTN = new List<MaBHYTTNModel>();
            using (Stream s = request.GetResponse().GetResponseStream())
            {
                using (StreamReader sr = new StreamReader(s))
                {
                    JavaScriptSerializer jsonserializer = new JavaScriptSerializer();
                    listMaBHYTTN = jsonserializer.Deserialize<List<MaBHYTTNModel>>(sr.ReadToEnd());
                    if (listMaBHYTTN.Count > 0)
                    {
                        datatable = getDataTable();
                        DataRow row;
                        List<string> listString = GetListNamColumn();
                        foreach (MaBHYTTNModel bhYTTN in listMaBHYTTN)
                        {
                            row = datatable.NewRow();
                            row["MaBHYTTN"] = bhYTTN.MaBHYTTN;
                            row["MaDotBH"] = bhYTTN.MaDotBH;
                            row["HoVaTen"] = bhYTTN.HoVaTen;
                            //row["NgaySinh"] = bhYTTN.NgaySinh;
                            row["GioiTinh"] = bhYTTN.GioiTinh;
                            //row["DiaChi"] = bhYTTN.DiaChi;
                            row["CoSoKCB"] = bhYTTN.CoSoKCB;
                            //row["TuNgay"] = bhYTTN.TuNgay;
                            //row["DenNgay"] = bhYTTN.DenNgay;
                            row["LoaiBH"] = bhYTTN.LoaiBH;
                            row["MucBH"] = bhYTTN.MucBH;
                            //row["NgayDangKy"] = bhYTTN.NgayDangKy;
                            //row["NgayCapThe"] = bhYTTN.NgayCapThe;
                            row["TinhTrang"] = bhYTTN.TinhTrang;
                            //row["GhiChu"] = bhYTTN.GhiChu;
                            row["DonViBHSTT"] = bhYTTN.DonViBHSTT;
                            row["MaSoThe"] = bhYTTN.MaSoThe;
                            row["NSD"] = bhYTTN.NguoiSudung;
                            //row["NgayTaoMoi"] = bhYTTN.NgayTaoMoi;
                            //row["NgayCapNhat"] = bhYTTN.NgayCapNhat;
                            datatable.Rows.Add(row);

                        }
                        btnExportExcel.Enabled = true;
                        btnPrintCard.Enabled = true;
                        GridView1.DataSource = datatable;
                        GridView1.DataBind();
                    }
                    else
                    {
                        btnExportExcel.Enabled = false;
                        btnPrintCard.Enabled = false;
                        GridView1.DataSource = datatable;
                        GridView1.DataBind();
                    }
                }
            }
        }

        private void GetLoaiBHModel()
        {
            List<LoaiBHModel> listLoaiBHModel = new LoaiBHModel().GetLoaiBHModel();
            foreach (LoaiBHModel loaiBHModel in listLoaiBHModel)
            {
                ddlLoaiBH.Items.Add(loaiBHModel.MaLoaiBH);
            }
        }

        public List<string> GetListNamColumn() {
            List<string> listStr = new List<string>();
            listStr.Add("MaBHYTTN");
            listStr.Add("MaDotBH");
            listStr.Add("HoVaTen");
            //listStr.Add("NgaySinh");
            listStr.Add("GioiTinh");
            //listStr.Add("DiaChi");
            listStr.Add("CoSoKCB");
            //listStr.Add("TuNgay");
            //listStr.Add("DenNgay");
            listStr.Add("LoaiBH");
            listStr.Add("MucBH");
            //listStr.Add("NgayDangKy");
            //listStr.Add("NgayCapThe");
            listStr.Add("TinhTrang");
            //listStr.Add("GhiChu");
            listStr.Add("DonViBHSTT");
            listStr.Add("MaSoThe");
            listStr.Add("NSD");
            //listStr.Add("NgayTaoMoi");
            //listStr.Add("NgayCapNhat");
            return listStr;
        }

        public DataTable getDataTable()
        {
            DataTable myTable = new DataTable("BHYTTN");
            DataColumn column;
            List<string> listString = GetListNamColumn();
            foreach (var item in listString)
            {
                column = new DataColumn();
                column.DataType = System.Type.GetType("System.String");
                column.ColumnName = item;
                column.ReadOnly = false;
                myTable.Columns.Add(column);
            }

            return myTable;
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            string id = GridView1.Rows[e.NewEditIndex].Cells[1].Text;
            Response.Redirect("DKBHTN.aspx?Id=" + id);
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string id = GridView1.Rows[e.RowIndex].Cells[1].Text;
            System.Net.WebRequest request = System.Net.WebRequest.Create(""+Util.getUrl() + "Home/deleteBHYTTN?id=" + id);
            request.Method = "POST";
            request.ContentLength = 0;
            request.ContentType = "application/json; charset=utf-8";
            //get response-stream, and use a streamReader to read the content
            Stream s = request.GetResponse().GetResponseStream();
            StreamReader sr = new StreamReader(s);
            string result = sr.ReadToEnd();
            if (result == "200")
            {
                //Label1.Text = "ok";
            }
            else
            {
                //Label1.Text = "error";
            }
            GetData("1");
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            GetData("2");
            maThe = txtMathe.Text;
            hoTen = txtHoTen.Text;
            loaiBH = txtHoTen.Text;
        }
        
        protected void btnPrint_Click(object sender, EventArgs e)
        {
            Response.Redirect("ReportCard.aspx?maThe=" + maThe + "&hoTen=" + hoTen + "&loaiBH=" + loaiBH);
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            GetData("2");
            export();
        }

        public void export()
        {
            // Create excel file.
            ExcelFile ef = new ExcelFile();
            ExcelWorksheet ws = ef.Worksheets.Add("DataSheet");
            ws.InsertDataTable(datatable, "A1", true);
            Response.Clear();
            string excel = "XLS";

            // Stream file to browser, in required type.
            switch (excel)
            {
                case "XLS":
                    Response.ContentType = "application/vnd.ms-excel";
                    Response.AddHeader("Content-Disposition", "attachment; filename=" +
                         "Danh_Sach_Cap_The_BH.xls");
                    ef.SaveXls(Response.OutputStream);
                    break;

                case "XLSX":
                    Response.ContentType = "application/vnd.openxmlformats";
                    Response.AddHeader("Content-Disposition", "attachment; filename=" +
                         "Danh_Sach_Cap_The_BH.xlsx");
                    MemoryStream ms = new MemoryStream();
                    ef.SaveXlsx(ms);
                    ms.WriteTo(Response.OutputStream);
                    break;
            }
            Response.End();
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            GetData("2");
        }

        protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            string id = GridView1.Rows[e.NewSelectedIndex].Cells[2].Text;
            Response.Redirect("DKBHTN.aspx?Madot=" + id + "&mode=add");
        }

        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            GetData("2");
            export();
        }

        protected void btnPrintCard_Click(object sender, EventArgs e)
        {
            Response.Redirect("ReportCard.aspx?maThe=" + maThe + "&hoTen=" + hoTen + "&loaiBH=" + loaiBH + "&dotBh=" + txtDotBH.Text + "&mucBH=0");
        }

    }
}
